<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 老猫 <thinkcmf@126.com>
// +----------------------------------------------------------------------
namespace app\admin\api;

use app\admin\model\NavMenuModel;

class NavMenuApi
{
    // 分类列表 用于模板设计
    public function index($param = [])
    {
        $navMenuModel = new NavMenuModel();

        $where = [];

        if (!empty($param['keyword'])) {
            $where['name'] = ['like', "%{$param['keyword']}%"];
        }
        if (!empty($param['id'])) {
            $where['nav_id'] = $param['id'];
        }
        return $navMenuModel->where($where)->order('list_order', 'asc')->select();
    }

    public function getFrontNav() {
        $navList = $this->index(['id' => 4])->toArray();
        // url
        $navList = $this->buildUrl($navList);
        $result = [];
        foreach ($navList as $nav) {
            if($nav['parent_id'] == 0 ) {
                $result[] = $nav;
            }
        }
        foreach ($result as &$item) {
            $item['sub'] = [];
            foreach ($navList as $nav) {
                if ($nav['parent_id'] == $item['id']) {
                    $item['sub'][] = $nav;
                }
            }
        }
        return $result;
    }

    private function buildUrl($navList) {
        foreach ($navList as &$nav) {
            if($nav['href'] == 'home') {
                $nav['href'] = '/';
                continue;
            }
            $params = json_decode($nav['href'], true);
            if(is_array($params)) {
                $nav['href'] = url($params['action'], $params['param']);
            }
        }
        return $navList;
    }
}